package com.tyj.movie.config.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tyj.movie.entity.Auth;
import com.tyj.movie.entity.Role;
import com.tyj.movie.entity.Users;
import com.tyj.movie.mapper.AuthMapper;
import com.tyj.movie.mapper.RoleMapper;
import com.tyj.movie.mapper.UsersMapper;
import com.tyj.movie.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 日期: 2021/6/7 10:50
 * 作者: 谭友杰
 * 类说明:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    AuthService authService;

    @Autowired
    UsersMapper userMapper;

    @Autowired
    AuthMapper authMapper;

    @Autowired
    RoleMapper roleMapper;



    /**
     * 注意 只会调用一次
     * @param name 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        //验证账号
        Users users = userMapper.selectOne(new QueryWrapper<Users>().eq("username",name));

        if (users==null){
            throw new BadCredentialsException("用户名不存在,请注册");
        }

        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();

//        查询当前角色
        List<Role> roles = roleMapper.selectRole(users.getId());

//        查询当前权限
        List<Auth> auths = authMapper.selectAuth(roles);

        for (Role role : roles) {
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            grantedAuthorities.add(simpleGrantedAuthority);
        }

        for (Auth auth : auths) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(auth.getAuth());
                grantedAuthorities.add(simpleGrantedAuthority);
        }

        UserDetails userDetails= new UserDetailsPacking(users,grantedAuthorities);



        return userDetails;
    }

}
